<template>
  <view class="wallet">
    <!-- 顶部余额渐变卡片 -->
    <view class="wallet-header">
      <view class="header-bg"></view>
      <view class="header-content">
        <view class="back-btn" @click="goBack" aria-label="返回" hover-class="back-btn--active">
          <svg viewBox="0 0 24 24" class="icon-back" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 18l-6-6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <text class="back-text">返回</text>
        </view>
        <text class="title">我的钱包</text>
        <view class="circle">
          <text class="num">{{ balanceDisplay }}</text>
          <text class="unit">H币</text>
        </view>
        <text class="sub">满2000H币可提现</text>
        <view class="header-actions">
          <button class="btn ghost" :loading="loading.withdraw" @click="goWithdraw">提现</button>
          <button class="btn solid" :loading="loading.recharge" @click="onRecharge">充值</button>
        </view>
      </view>
    </view>

    <!-- 充值表单已迁移至独立页面，此处不再展示金额输入与渠道选择 -->

    <!-- 提现金额输入 -->
    <view class="withdraw-card">
      <view class="withdraw-title">提现金额</view>
      <view class="withdraw-row">
        <text class="currency">H币</text>
        <input class="withdraw-input" type="number" v-model.number="amount" :focus="withdrawInputFocus" @blur="onWithdrawInputBlur" placeholder="请输入提现金额" />
        <button class="all-btn" size="mini" @click="fillAll">全部</button>
      </view>
      <view class="withdraw-note">满2000H币起，且为10的倍数，不超过当前余额</view>
      <view class="withdraw-actions">
        <button class="primary" :loading="loading.withdraw" @click="onWithdraw">确认提现</button>
      </view>
    </view>

    <view class="record-card">
      <view class="record-title">我的充值/提现记录</view>
      <view v-if="loading.records" class="record-loading">加载中...</view>
      <view v-else>
        <view v-if="records.length === 0" class="record-empty">暂无记录</view>
        <view v-else>
          <uni-swipe-action>
            <uni-swipe-action-item
              v-for="item in records"
              :key="item.id"
              :right-options="swipeRightOptions"
              @click="onSwipeClick($event, item)"
            >
              <view class="record-item">
                <view class="left">
                  <view class="type" :class="{ in: item.type === 1, out: item.type === 2 }">{{ typeText(item.type) }}</view>
                  <view class="time">{{ item.createTime }}</view>
                </view>
                <view class="right" :class="{ in: item.type === 1, out: item.type === 2 }">
                  {{ item.type === 1 ? '+' : '-' }}{{ item.money }}
                </view>
              </view>
            </uni-swipe-action-item>
          </uni-swipe-action>
          <view class="load-more" v-if="hasMore">
            <button size="mini" @click="loadMore" :disabled="loading.records">加载更多</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getMyHcoin, withdrawHcoin, getMyRechargeRecords, deleteRechargeRecord } from '@/api/patient.js'

export default {
  name: 'WalletRecharge',
  data() {
    return {
      balance: 0,
      amount: null,
      withdrawInputFocus: false,
      records: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      hasMore: true,
      loading: {
        balance: false,
        recharge: false,
        withdraw: false,
        records: false
      },
      swipeRightOptions: [
        { text: '删除', style: { backgroundColor: '#ff3b30', color: '#fff' } }
      ]
    }
  },
  computed: {
    balanceDisplay() {
      return typeof this.balance === 'number' ? this.balance : '-'
    }
  },
  onShow() {
    this.init()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.resetPaging()
    Promise.all([this.fetchBalance(), this.fetchRecords(false)])
      .finally(() => uni.stopPullDownRefresh())
  },
  // 触底加载更多
  onReachBottom() {
    if (!this.hasMore || this.loading.records) return
    this.pageNum += 1
    this.fetchRecords(true)
  },
  methods: {
    goBack() {
      // 优先返回上一页，若失败则回到“我的”tab
      uni.navigateBack({
        delta: 1,
        fail: () => {
          uni.switchTab({ url: '/pages/mine/index' })
        }
      })
    },
    async init() {
      this.resetPaging()
      await Promise.all([this.fetchBalance(), this.fetchRecords(false)])
    },
    async fetchBalance() {
      try {
        this.loading.balance = true
        const res = await getMyHcoin()
        this.balance = res?.data ?? 0
      } catch (e) {
        uni.showToast({ title: '获取余额失败', icon: 'none' })
      } finally {
        this.loading.balance = false
      }
    },
    resetPaging() {
      this.pageNum = 1
      this.total = 0
      this.hasMore = true
      this.records = []
    },
    async fetchRecords(append = true) {
      try {
        this.loading.records = true
        const res = await getMyRechargeRecords({ pageNum: this.pageNum, pageSize: this.pageSize })
        const list = Array.isArray(res?.rows) ? res.rows : []
        const total = Number(res?.total || 0)
        if (append) {
          this.records = this.records.concat(list)
        } else {
          this.records = list
        }
        this.total = total
        this.hasMore = this.records.length < this.total
      } catch (e) {
        uni.showToast({ title: '获取记录失败', icon: 'none' })
      } finally {
        this.loading.records = false
      }
    },
    loadMore() {
      if (!this.hasMore || this.loading.records) return
      this.pageNum += 1
      this.fetchRecords(true)
    },
    async onSwipeClick(e, item) {
      // e.content.text 为按钮文本
      if (!item || !item.id) return
      if (e?.content?.text !== '删除') return
      const confirm = await new Promise((resolve) => {
        uni.showModal({
          title: '确认删除',
          content: '删除后不可恢复，是否继续？',
          confirmText: '删除',
          confirmColor: '#ff3b30',
          success: (res) => resolve(res.confirm === true)
        })
      })
      if (!confirm) return
      try {
        this.loading.records = true
        await deleteRechargeRecord(item.id)
        // 简单做法：重载第一页，保证分页与总数一致
        this.resetPaging()
        await this.fetchRecords(false)
        uni.showToast({ title: '已删除', icon: 'success' })
      } catch (err) {
        const msg = err?.msg || err?.message || '删除失败'
        uni.showToast({ title: msg, icon: 'none' })
      } finally {
        this.loading.records = false
      }
    },
    fillAll() {
      const bal = Number(this.balance)
      if (!Number.isFinite(bal) || bal <= 0) {
        uni.showToast({ title: '余额不足，至少10H币可提现', icon: 'none' })
        return
      }
      if (bal < 2000) {
        uni.showToast({ title: '最低提现2000H币起', icon: 'none' })
        this.amount = null
        // 不中断频繁切换focus，避免闪烁
        this.withdrawInputFocus = true
        return
      }
      if (this.isMultipleOf10(bal)) {
        // 余额本身满足规则，直接映射
        this.amount = bal
      } else {
        // 不满足10的倍数时，取不超过余额的最大可提现金额
        const max = Math.floor(bal / 10) * 10
        this.amount = max
        uni.showToast({ title: `余额需为10的倍数，已为您填充${max}H币`, icon: 'none' })
      }
      // 自动聚焦到输入框（不再快速切换，避免闪烁）
      this.withdrawInputFocus = true
    },
    validAmount() {
      if (this.amount == null || this.amount === '') {
        uni.showToast({ title: '请输入提现金额', icon: 'none' })
        return false
      }
      const n = Number(this.amount)
      if (!Number.isFinite(n)) {
        uni.showToast({ title: '提现金额格式不正确', icon: 'none' })
        return false
      }
      if (n <= 0) {
        uni.showToast({ title: '提现金额需大于0', icon: 'none' })
        return false
      }
      if (n < 2000) {
        uni.showToast({ title: '最低提现2000H币起', icon: 'none' })
        return false
      }
      return true
    },
    isMultipleOf10(n) {
      return Number(n) % 10 === 0
    },
    genRequestId() {
      // 简易 requestId：时间戳 + 随机数
      return `${Date.now()}_${Math.random().toString(36).slice(2, 10)}`
    },
    async onRecharge() {
      // 跳转到独立充值页，由新页面完成支付方式选择与下单
      const n = this.amount
      const qs = n != null && n !== '' ? `?amount=${encodeURIComponent(n)}` : ''
      uni.navigateTo({ url: `/pages/wallet/pay${qs}` })
    },
    goWithdraw() {
      // 聚焦到提现输入框（不再做快速开关）
      this.withdrawInputFocus = true
    },
    onWithdrawInputBlur() {
      // 失焦后再复位，避免卡顿闪烁
      this.withdrawInputFocus = false
    },
    async onWithdraw() {
      if (!this.validAmount()) return
      if (!this.isMultipleOf10(this.amount)) {
        uni.showToast({ title: '提现金额必须为10的倍数', icon: 'none' })
        return
      }
      if (Number(this.amount) > Number(this.balance)) {
        uni.showToast({ title: '余额不足', icon: 'none' })
        return
      }
      try {
        this.loading.withdraw = true
        const requestId = this.genRequestId()
        await withdrawHcoin(this.amount, requestId)
        uni.showToast({ title: '提现成功', icon: 'success' })
        this.amount = null
        this.resetPaging()
        await Promise.all([this.fetchBalance(), this.fetchRecords(false)])
      } catch (e) {
        const msg = e?.msg || e?.message || '提现失败'
        uni.showToast({ title: msg, icon: 'none' })
      } finally {
        this.loading.withdraw = false
      }
    },
    typeText(type) {
      return type === 1 ? '充值' : type === 2 ? '提现' : '其他'
    }
  }
}
</script>

<style lang="scss" scoped>
.wallet {
  min-height: 100vh;
  background: #f5f6f7;
  padding-bottom: 40rpx;
}

/* 顶部渐变余额卡片 */
.wallet-header {
  position: relative;
  height: 420rpx;
  border-bottom-left-radius: 24rpx;
  border-bottom-right-radius: 24rpx;
  overflow: hidden;
  /* 为下方内容预留间距，避免覆盖 */
  margin-bottom: 16rpx;
  .header-bg {
    position: absolute;
    inset: 0;
    background: linear-gradient(180deg, #3c7bff 0%, #4aa3ff 100%);
  }
  .header-content {
    position: relative;
    z-index: 1;
    height: 100%;
    /* 顶部加入安全区，避免被刘海遮挡 */
    padding: calc(24rpx + env(safe-area-inset-top, 0px)) 32rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #fff;
    .back-btn {
      position: fixed;
      left: 20rpx;
      top: calc(env(safe-area-inset-top, 0px) + 16rpx);
      /* 兼容旧 WebView 的安全区写法 */
      top: calc(constant(safe-area-inset-top, 0px) + 16rpx);
      min-width: 120rpx; height: 64rpx;
      padding: 0 20rpx;
      border-radius: 9999rpx;
      background: rgba(0,0,0,0.55);
      border: 1px solid rgba(255,255,255,0.7);
      box-shadow: 0 6rpx 14rpx rgba(0,0,0,0.25);
      backdrop-filter: blur(6px);
      display: flex; align-items: center; gap: 10rpx; justify-content: center;
      color: #fff;
      z-index: 999;
      .icon-back { width: 36rpx; height: 36rpx; display: block; }
      .back-text { font-size: 26rpx; }
    }
    .back-btn--active { opacity: .8; }
    .title { font-size: 32rpx; opacity: .95; }
    .circle {
      width: 200rpx; height: 200rpx; border-radius: 50%;
      background: rgba(255,255,255,0.18);
      margin: 20rpx 0 12rpx;
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      .num { font-size: 56rpx; font-weight: 700; line-height: 1; }
      .unit { margin-top: 8rpx; font-size: 24rpx; opacity: .9; }
    }
    .sub { font-size: 24rpx; opacity: .9; }
    .header-actions { display: flex; gap: 28rpx; margin-top: 20rpx; }
    .btn {
      min-width: 180rpx; height: 72rpx; line-height: 72rpx; border-radius: 999rpx; font-size: 28rpx;
    }
    .btn.solid { background: #ffffff; color: #3c7bff; }
    .btn.ghost { background: transparent; color: #fff; border: 2rpx solid rgba(255,255,255,.9); }
    
  }
}

/* 表单卡片 */
/* 提现卡片 */
.withdraw-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin: 0 24rpx 16rpx;
  .withdraw-title { font-size: 30rpx; font-weight: 600; margin-bottom: 12rpx; }
  .withdraw-row {
    display: flex; align-items: center; gap: 16rpx;
    background: #f7f8fa; border-radius: 12rpx; padding: 16rpx;
    .currency { color: #333; font-size: 28rpx; }
    .withdraw-input { flex: 1; font-size: 32rpx; background: transparent; }
    .all-btn { margin-left: 8rpx; }
  }
  .withdraw-note { color: #999; font-size: 24rpx; margin-top: 8rpx; }
  .withdraw-actions { margin-top: 16rpx; }
  .primary { width: 100%; height: 80rpx; line-height: 80rpx; background: #3c7bff; color: #fff; border-radius: 12rpx; }
}

/* 记录卡片 */
.record-card {
  background: #fff; border-radius: 20rpx; padding: 24rpx; margin: 0 24rpx;
  .record-title { font-size: 30rpx; font-weight: 600; margin-bottom: 4rpx; }
  .record-loading, .record-empty { color: #999; font-size: 26rpx; padding: 24rpx 0; text-align: center; }
  .record-item { display: flex; align-items: center; justify-content: space-between; padding: 22rpx 0; border-bottom: 1px solid #f0f2f5; }
  .record-item:last-child { border-bottom: 0; }
  .left { display: flex; flex-direction: column; }
  .type { font-size: 28rpx; margin-bottom: 6rpx; color: #333; }
  .time { color: #999; font-size: 24rpx; }
  .right { font-size: 32rpx; font-weight: 700; }
  .right.in { color: #07c160; }
  .right.out { color: #fa5151; }
  .load-more { text-align: center; padding: 12rpx 0; }
}
</style>
